import { init } from '@/utils/api';
import { GetUrlParam } from '@/utils/utils'
import { wxlogin } from '@/utils/api';

export async function initConfig() {
	const configInfo = uni.getStorageSync('configInfo')
	let respStorage : any = configInfo ? JSON.parse(configInfo) : ''
	console.log('respStorage', respStorage)
	if (respStorage?.code !== 1) {
		respStorage = await init();
		uni.setStorageSync('configInfo', JSON.stringify(respStorage));
	}

	return respStorage;
}

export function setPageTitle(title : string) {
	title && uni.setNavigationBarTitle({
		title: title
	});
}

export async function getToken() {
	const token = await uni.getStorageSync('token')
	return token;
}

// 保存token、avatar、nickname
export async function saveUserinfo() {
	const paramCode = GetUrlParam('code');
	const token = await uni.getStorageSync('token')
	if (!token && paramCode) {
		const { code, data } = await wxlogin(paramCode)
		if (code == 1) {
			uni.setStorageSync('token', data.token)
			uni.setStorageSync('avatar', data.avatar)
			uni.setStorageSync('nickname', data.nickname)
		}
		console.log('token', uni.getStorageSync('token'))
	}
}

export async function getAvatar() {
	const avatar = await uni.getStorageSync('avatar') || '/static/avatar.png';
	return avatar;
}

export async function getNickname() {
	const nickname =await uni.getStorageSync('nickname');
	return nickname;
}